var $tbody = $("#sample-table-1 tbody");
var allStation = [];
	// 初始化table
	$("#label_table").bootstrapTable({
	    'url': '/community/forumMessageLabel/queryAllForumMessageLabel',     
	    'toolbar': $('div[data-name="btnCtl"]'),
	    /*'queryParams':function(params){
	    	params["stationId"]=$("#stationSelects").val();
	    	return params;
	    },*/
	    'cache':false,
	    'toolbarAlign': 'right',
	    'striped': true,
	    'pagination': true,
		'sortable': true, //是否启用排序
		'sortOrder': "asc", //排序方式
		'sidePagination': 'client',
	    'pageSize': globalPageSize,
	    'pageList': [],
	    'clickToSelect': true,
	    'singleSelect': true,
	    'smartDisplay': true,
	    /*'responseHandler': function (resb) {
	        return {
	            'total': resb.data.length,
	            'rows': resb.data,
	        }
	    },	 */  
	    'onCheck': function() {
	        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").removeAttr("disabled");
	    },
	    'onUncheck': function() {
	        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
	    },
	    'onPageChange': function() {
	    	if($("#label_table").bootstrapTable('getSelections')[0]){
	    		$("#label_table").bootstrapTable('uncheckBy', {
	                field: 'typeId',
	                values: [$("#label_table").bootstrapTable('getSelections')[0].typeId]
	            });
	    	}
	        
	    },
	    'columns': [{
	        'checkbox': true,
	       // 'class': 'hide'
	    }, 
	    {
	        'field': 'forumMessageLabelId',
	        'title': '类型',
	        'width':150,
	        'class':'hide',
	        'align': 'center'
	      
	       
	    },
	    {
	        'field': 'labelDescribe',
	        'title': '描述',	        
	        'align': 'center'
	       
	    },{
	        'field': 'labelStatus',
	        'title': '状态',
	        'align': 'center',
	        'formatter':function(labelStatus){
	        	if(labelStatus =='0'){
	        		labelStatus = '启用';
	        	}
	        	else if(labelStatus =='1') {
	        		labelStatus='停用';
	        	}
	        	return labelStatus ===null ?  '未知' : labelStatus;
	        }
	        
	    },{
	        'field': 'orderNo',
	        'title': '排序',	        
	        'align': 'center'
	       
	    },{
	        'field': 'createDate',
	        'title': '创建时间',	        
	        'align': 'center'
	       
	    }	    
	    ]
	});

/**
 * 标签查询ajax
 * @param labelDescribe
 */
function labelQuery(labelDescribe) {
	if(($("#inputStation").val()== '')){
		$('#label_table').bootstrapTable('refreshOptions',{pageNumber:1,pageSize:globalPageSize});
	}else{
	$.ajaxSetup({cache:false});
    $.ajax({
        type: "POST",
        url: "/community/forumMessageLabel/getSearcherForummessagelabel",
        data: {           
            "labelDescribe": labelDescribe
        },        
        dataType: 'json',       
        success: function(resb) { 
        	 if (resb.data.length != 0) {  
                 $("#label_table").bootstrapTable('load', resb.data);
             } else {
                 $("#label_table").bootstrapTable('removeAll');
             }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
	}
    return false;
}




/**
 * 角色操作(新增，更新，删除)
 * @param action [add/update/remove]
 * @param data
 *               [add/update 数据结构 {name: string, description: string, listAuthorityId: array} ]
 *               [delete 数据结构 {roleId: int}]
 * @param async/scync [default async]
 */
function labelManagement(action, data, async) {
    var url = null;
    (async === false) ? async = false: async = true;
    if (action === 'add') {
        url = '/community/forumMessageLabel/saveForumMessageLabel';
    } else if (action === 'update') {
        url = '/community/forumMessageLabel/updateForumMessageLabel';
    } else {
        url = '/community/forumMessageLabel/deleteForumMessageLabel';
    };
    return $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(data),
        traditional:true,
        contentType:"application/json",
        dataType: 'json',
        async: async,
        success: function(resb) {
            alert(resb.message);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            alert(textStatus);
        }
    });
}

$(document).on('click','.spanIcons',function(){
	$('#inputStation').val("");
	if($('#inputStation').val() ==""){
		$('.spanIcons').removeClass('glyphicon glyphicon-remove');
	}
});
$("#inputStation").keyup(function(){
	if($('#inputStation').val() !=""){
		$('.spanIcons').addClass('glyphicon glyphicon-remove');
	}
	if($('#inputStation').val() ==""){
		$('.spanIcons').removeClass('glyphicon glyphicon-remove');
	}
})



/**
 * 查询表单提交
 */
$("#dataSearch").on('click',function() {	
    return labelQuery($("#inputStation").val());
});

//$("#stationFormId").submit(function() {
//    return serviceQueryByStationId($("#serviceProviderSel").val());
//});

/**
 * 新增模态框显示
 */
$("#addModal").on('show.bs.modal', function() {
	 $(this).find("input[type=text]").val("");
});

/**
 * 删除模态框显示
 */
$("#deleteModal").on('show.bs.modal', function() {
    var name = $("#label_table").bootstrapTable('getSelections')[0].labelDescribe,
        html = '你确定要删除标签: <span>' + name + '</span>?';
    $(this).find('div.modal-body').empty().append(html);
});

/**
 * 更新模态框显示
 */

$("#updateModal").on('show.bs.modal', function() {
    var $that = $(this),
        $inputs = $that.find("input[type=text]"),
       
        tableData = $("#label_table").bootstrapTable("getSelections")[0],
        roleAuth = {};  
    var $status = $(this).find('select[name="labelStatus"]');
	var $orderNo = $(this).find('select[name="orderNo"]');
		
    // 设置ID,姓名,帐号,电话,年龄
	$inputs[0].value = tableData.forumMessageLabelId;
    $inputs[1].value = tableData.labelDescribe;
    $status.val(tableData.labelStatus);
    $orderNo.val(tableData.orderNo);
      
});

/**
 * 新增,更新,删除角色表单提交
 */
$("button[name=submit]").on('click',function() {
    var type = $(this).data("type"),
        $modal = $("#" + type + "Modal"),
        $inputs = $modal.find('input[type="text"]'),
           
        //$checkboxs = $(this).find('input[type="checkbox"]').prop('checked',true),
        tableData = $("#label_table").bootstrapTable("getSelections")[0],
        data = null,
        $that = $(this);
    
   
    // 模式选择,设置不同的data和url
    if (type === 'delete') {
    	data = {
    		'id': tableData.forumMessageLabelId
    		
    	};
    } else if (type === 'add') {
    	var obj = jQuery("#addForm").validationEngine('validate', {promptPosition : "centerRight", autoPositionUpdate : true});
    	if(!obj){
    		return false;
    	};
    	var $status = $modal.find('select[name="labelStatus"]');
    	var $orderNo = $modal.find('select[name="orderNo"]');
    	data = {    
    			
    			//'forumMessageLabel':$inputs[0].value,
    			
    			'labelDescribe': $inputs[1].value,
    			'labelStatus':$status.val(),
    	        'orderNo':$orderNo.val()
    	        
    	};
    } else if (type ==='update') {  
    	var $status = $modal.find('select[name="labelStatus"]');
    	var $orderNo = $modal.find('select[name="orderNo"]');  
        data = {        	           
        		'labelDescribe': $inputs[1].value,
    			'labelStatus':$status.val(),
    	        'orderNo':$orderNo.val()
  	            
        };
        data['forumMessageLabelId'] = tableData.forumMessageLabelId;
    };
 

    $modal.modal('hide');
    // 完成ajax后刷新表格数据
    labelManagement(type, data).done(function() {
        $("#label_table").bootstrapTable("refresh");
        $("button[data-target='#updateModal'], button[data-target='#deleteModal']").attr("disabled", 'true');
       /* $that.get(0).reset();*/
    });

    // 阻止表格冒泡事件
    return false;
});
